import React, { Component } from 'react';
import {
    StyleSheet, Text, View, TouchableOpacity, Image, PixelRatio, ActivityIndicator
} from "react-native";
import DatePicker from 'react-native-datepicker'
import ImagePicker from 'react-native-image-picker';
import { GLOBAL } from '../../../../config/global';
import MethodUtil from '../../../../utils/MethodUtil';
import { style } from '../../../../theme/style';
import { API, API_GENERATE } from '../../../../config/api';
import Upload from '../../../../utils/Upload';
import HTTP from '../../../../utils/http';
import ModalPicDelComponent from '../../../../component/ModalPicDelComponent';
import navigationSeevice from '../../../../components/navigation/navigationSeevice';

const scale = GLOBAL.SCALE;
const statusObj = {
    null: { key: 'null', status: '未认证', operate: '认证', color: '#0E5BC6' },
    usable: { key: 'usable', status: '已认证', operate: '', color: '#19977B' },
    isexpired: { key: 'isexpired', status: '已过期', operate: '认证', color: '#AAB1BF' },
}
const uploadPic = require('../../../../imgs/store/upload.png');
let defaultImg = require('../../../../imgs/addphoto.png');
let deleteIcon = require('../../../../imgs/delete2.png');
let downAccount = require('../../../../imgs/downAccount2.png')
const modalPicDelCfg = {
    visible: false,
    uri: null,
    delPress: () => { },
    picPress: () => { },
    fileId: '',
    delTextHide: true
}
export class EnterpriseUploadItem extends Component {
    constructor(props) {
        super(props);
        const { expireDate, companyId, qualificationType, isAuditing, qualificationTypeText, isNew, isAuditTag } = props.data || '';
        this.state = {
            loading: false,
            uriList: [],
            expireDate: expireDate && expireDate.substring(0, 10) || ''
        }
        modalPicDelCfg.picPress = () => {
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;
            this.setState({
                previewModalVisible: false,
            });
        }
        this.showData = {
            qualificationTypeText,
            qualificationType,
            uriListUri: []
        }
        this.itemData = {
            companyId,
            qualificationType,
            isAuditing,
            isAuditTag,
            qualificationTypeText,
            isNew
        }
    }
    async componentWillMount() {
        const { qualificationAddress } = this.props.data;
        qualificationAddress && this.getImgView(qualificationAddress);
    }
    getItemValue = () => {
        let { uriList, expireDate } = this.state
        let qualificationAddress = '';
        this.showData.uriListUri = []
        uriList.forEach((item, i) => {
            if (item) {
                qualificationAddress += (i === 0 ? '' : ',') + item.fileId;
            }
            if (this.itemData.isNew) {
                if (item.type === 'PDF') {
                    this.showData.uriListUri.push(
                        'pdf:' + item.fileId
                    )
                }
                else {
                    this.showData.uriListUri.push(
                        item.uri
                    )
                }
            }
        })
        this.itemData.qualificationAddress = qualificationAddress
        this.itemData.expireDate = expireDate
        this.props.getItemInfo({ itemData: this.itemData, showData: this.showData })
    }
    _checkStatus(data) {
        let { qualificationAddress, isExpired, isAuditing } = data || {};
        let lsObj = JSON.stringify(statusObj);
        lsObj = JSON.parse(lsObj);
        if (qualificationAddress) {
            if (isExpired == '-1') {
                return lsObj['isexpired'];
            } else {
                if (isAuditing) {
                    return lsObj['null'];
                } else {
                    return lsObj['usable'];
                }
            }
        } else {
            return lsObj['null'];
        }
    }
    //提前获取资质图片
    getImgView(qualificationAddress) {
        if (!qualificationAddress) return;
        this.setState({ loaded: true })
        const qualificationArr = qualificationAddress.split(',');
        qualificationArr.map(async (fileId, index) => {
            await this.loadedImgs(fileId, qualificationArr.length, index);
        })
    }
    async loadedImgs(fileId, length, index) {
        const { uriList } = this.state;
        const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
        if (response) {
            const { attachmentFileVO } = response;
            uriList.push({
                uri: response.image || '',
                type: attachmentFileVO.fileExtName.toUpperCase() || 'PNG',
                fileId
            });
            if (uriList.length == length) {
                this.setState({
                    loaded: false,
                });
            }
        } else {
            this.setState({ loaded: false })
        }
    }
    selectPhotoTapped(ocrType) {
        let imgRep = {};
        const options = {
            title: '请选择图片来源',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册图片',
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true,
                // path: 'images'
            },
            mediaType: 'photo',
        };
        ImagePicker.showImagePicker(options, async (response) => {
            const { uriList } = this.state;
            if (response.didCancel) {
                console.log('User cancelled photo picker');
                return;
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
                return;
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
                return;
            }
            else {
                imgRep.uri = response.uri;
                this.setState({
                    loaded: true
                });
            }
            const uploadImgObj = {
                imgUrl: { uri: response.uri },
                url: API_GENERATE(API.IMG_UPLOAD)
            }
            if (ocrType && ocrType.length) {
                uploadImgObj.ocrType = ocrType;
                uploadImgObj.isOcr = 1;
            } else {
                uploadImgObj.isOcr = 0
            }
            let responseData = await Upload.uploadImg(uploadImgObj);

            if (responseData) {
                if (responseData.fileId) {
                    imgRep.fileId = responseData.fileId;
                    imgRep.type = 'PNG';
                    this.itemData.isNew = true
                    uriList.push(imgRep);
                    this.getItemValue()
                }
            }
            this.setState({
                loaded: false
            })
        });
    }
    async _delete(index, fileId) {
        const { uriList } = this.state;
        if (!fileId) return;
        uriList.splice(index, 1);
        this.setState({ uriList }, () => {
            this.getItemValue()
        });
    }

    render() {
        let { data } = this.props || {};
        let status = data && this._checkStatus(data);
        let { uriList, expireDate, loaded } = this.state;
        return (
            <View style={styles.itemBox}>
                <View style={styles.item}>
                    <View><Text style={styles.lableText}>{data.qualificationTypeText}</Text></View>
                    <View style={styles.rightView}>
                        {data.isAuditTag ? <View style={styles.auditingBorder}><Text style={styles.auditingText}>审</Text></View> : null}
                        <View style={[styles.circle, { backgroundColor: status.color }]}></View>
                        <Text style={styles.commonText}>{status.status}</Text>
                    </View>
                </View>
                <View style={styles.attachmentRow}>
                    {uriList.length ? uriList.map((item, i) => {
                        const { uri, fileId, type } = item;
                        return (
                            <TouchableOpacity key={i} style={[styles.attachment, styles.uploadImgBox]}
                                onPress={() => {
                                    if (type == 'PDF') {
                                        navigationSeevice.navigate('ContractPdfPage', {
                                            finalFileId: fileId,
                                            title: '附件信息'
                                        })
                                    } else {
                                        this.props.enlarge(uri)
                                    }

                                }} activeOpacity={0.5}>
                                <TouchableOpacity onPress={this._delete.bind(this, i, fileId)} style={styles.close}>
                                    <Image style={styles.closeImg} source={deleteIcon} />
                                </TouchableOpacity>
                                {
                                    type == 'PDF' ?
                                        <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap' }}>
                                            <Text style={{ fontSize: 12 * scale }}>PDF文件</Text>
                                            <Text style={{ fontSize: 10 * scale }}>点击可查看</Text>
                                        </View>
                                        : <Image source={type == 'ERROR' ? deleteIcon : item} style={styles.covermax} />
                                }

                            </TouchableOpacity>
                        )
                    }) : null}
                    <TouchableOpacity style={styles.attachmentAdd} onPress={() => {
                        this.selectPhotoTapped(0);
                    }} activeOpacity={0.5} >
                        <Image source={defaultImg} style={styles.cover} />
                    </TouchableOpacity>

                </View>
                <View style={styles.boxUp}>
                    <Text style={styles.require}>有效期至</Text>
                    <View style={styles.rowStyle}>
                        <DatePicker
                            style={{ width: 128 }}
                            date={expireDate}
                            mode="date"
                            placeholder="请选择结束日期"
                            format="YYYY-MM-DD"
                            confirmBtnText="确认"
                            cancelBtnText="取消"
                            customStyles={{
                                dateIcon: { opacity: 0, width: 0 },
                                dateInput: {
                                    marginLeft: 0, borderWidth: 0, alignItems: 'center'
                                }
                            }
                            }
                            onDateChange={(date) => {
                                this.setState({
                                    expireDate: date
                                }, () => {
                                    this.getItemValue()
                                })
                            }}
                        />
                    </View>
                    <Image source={downAccount} style={styles.downAccount} />
                </View>
                {
                    loaded ?
                        <View style={styles.loadingView}>
                            <View style={styles.loadedCell}>
                                <ActivityIndicator
                                    animating={true}
                                    color={'#fff'}
                                    size="small"
                                />
                            </View>
                        </View> : null
                }
            </View>
        )
    }
}
const styles = StyleSheet.create({
    itemBox: {
        marginBottom: 20 * scale,
    },
    item: {
        paddingHorizontal: 12 * scale,
        paddingTop: 20 * scale,
        paddingBottom: 20 * scale,
        paddingRight: 20 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    lableText: {
        fontSize: 12 * scale,
        color: '#000'
    },
    border: {
        borderBottomWidth: 1 * scale,
        borderBottomColor: '#E3E7F0'
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        // paddingLeft: 6 * scale,
        paddingBottom: 8 * scale,
    },
    qualificationText: {
        fontSize: 12 * scale,
        // color: style.color.themeColor
    },
    circle: {
        width: 7 * scale,
        height: 7 * scale,
        borderRadius: 7 * scale,
        marginRight: 5 * scale
    },
    commonText: {
        fontSize: 12 * scale,
        color: '#34475F',
        // marginRight: 10 * scale,
        borderBottomWidth: 1 * scale,
        borderBottomColor: '#E3E7F0',
        fontWeight: 'bold'
    },
    usableText: {
        fontSize: 10 * scale,
        color: '#BBBDC0',
    },
    expiredBtn: {
        fontSize: 12 * scale,
        color: style.color.themeColor,
        fontWeight: 'bold'
    },
    rightView: {
        // width: 64 * scale,
        flexDirection: 'row',
        alignItems: 'center',
    },
    auditingText: {
        color: '#F7B500',
        fontSize: 12 * scale,
        marginTop: 2 * scale,
    },
    auditingBorder: {
        height: 18 * scale,
        width: 18 * scale,
        marginRight: 5 * scale,
        borderWidth: 1 * scale,
        borderColor: '#F7B500',
        borderRadius: 14 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    preview: {
        height: GLOBAL.SCREEN_HEIGHT,
        backgroundColor: 'rgba(0,0,0,.5)',
        alignItems: 'center',
        justifyContent: 'center'
    },
    changeText: {
        color: style.color.fontRed1,
        fontSize: 12 * scale,
        paddingLeft: 3 * scale
    },
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
    },
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    wrap: {
        width: 345 * scale,
    },
    closeTextCell: {
        position: 'absolute',
        left: 8,
        top: 0,
    },
    productText: {
        fontSize: 14 * scale,
        color: '#404040',
        marginBottom: 8 * scale,
        paddingTop: 14 * scale,
        lineHeight: 14 * scale,
    },
    ocrWrap: {
        width: 375 * scale,
        height: GLOBAL.SCREEN_HEIGHT,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadedCell: {
        width: 75 * scale,
        height: 75 * scale,
        backgroundColor: 'rgba(0, 0, 0, .5)',
        borderRadius: 7,
        justifyContent: 'center',
        alignItems: 'center',
        position: 'absolute',
        top: '50%',
        left: '50%',
        marginTop: -37.5,
        marginLeft: -37.5
    },
    boxUp: {
        marginLeft: 12 * scale,
        width: 250 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        // paddingTop: 5 * scale,
        // paddingBottom: 5 * scale,
        borderBottomWidth: 1,
        borderStyle: 'solid',
        borderBottomColor: '#000',
    },
    label: {
        width: 70 * scale,
        color: '#333',
        fontSize: 14 * scale
    },
    require: {
        fontSize: 14 * scale,
    },
    rowStyle: {
        // flex: 1,
        flexDirection: 'row',
        alignItems: 'center'
    },
    uploadImgBox: {
        //borderColor: style.color.themeColor,
        //borderWidth: 1 / PixelRatio.get(),
        width: 60 * scale,
        height: 60 * scale,
        marginTop: -10 * scale,
        position: 'relative'
    },
    close: {
        position: 'absolute',
        right: 6 * scale,
        top: 6 * scale,
        width: 12 * scale,
        height: 12 * scale,
        zIndex: 10,

    },
    closeImg: {
        width: 12 * scale,
        height: 12 * scale,
    },
    attachmentRow: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginLeft: 18 * scale,
    },
    cover: {
        width: 60 * scale,
        height: 60 * scale,
        // marginLeft:3 * scale,
    },
    covermax: {
        width: 49 * scale,
        height: 49 * scale,
        marginTop: 10 * scale
    },
    attachment: {
        marginLeft: 8 * scale,
        marginBottom: 10 * scale,
    },
    attachmentAdd: {
        // width: 50 * scale,
        // height: 50 * scale,
        marginLeft: 5 * scale,
        marginTop: -5 * scale
    },
    downAccount: {
        width: 15 * scale,
        height: 15 * scale,
        tintColor: '#000',
        marginLeft: 50 * scale,
    },
    loadingView: {
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.1)',
        position: 'absolute',
    },
})